package com.gitee.feizns.quickstart.web.ex.impl;

import com.gitee.feizns.quickstart.domain.vo.Ret;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

/**
 * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
 *
 * <p>
 *     在SpringMvc中 JSR303 数据校验出现未通过的情况
 *     会统一抛出 BindException BindExceptionHandler
 *     则对所以数据校验上的错误进行统一处理
 * </p>
 *
 * @link <a href="https://juejin.cn/post/6844904003684302861">Spring 参数校验的异常处理</a>
 * @see BindException
 * @author feizns
 * @since 2019/7/7
 */
@NoArgsConstructor
public class BindExceptionHandler extends AbstractExceptionHandler<BindException> {

    /**
     * 响应的Http状态
     */
    private HttpStatus httpStatus = HttpStatus.BAD_REQUEST;

    public BindExceptionHandler(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }

    @Override
    public ResponseEntity<Ret<?>> handle(BindException e) {
        return ResponseEntity.status(httpStatus)
                .body(Ret.error(httpStatus.value(), getDefaultMessage(e)));
    }

    private static String getDefaultMessage(BindException e) {
        FieldError error = e.getBindingResult().getFieldError();
        if ( error != null )
            return  String.format("参数:[%s]%s.", error.getField(), error.getDefaultMessage());
        return e.getMessage();
    }

}
